package com.denlaku.longan.lock;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import org.jspecify.annotations.NonNull;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.concurrent.locks.ReentrantLock;

/**
 *
 * @author tianx
 */
@Component
@ConditionalOnProperty(prefix = "longan", value = "deployMode", havingValue = "SINGLE")
public class LocalLockFactory implements LockFactory {
    private final Cache<@NonNull String, LocalLock> lockMap = Caffeine.newBuilder()
            .initialCapacity(5)
            .maximumSize(10)
            .expireAfterWrite(Duration.ofHours(1))
            .build();

    @Override
    public Lock getLock(String name) {
        return lockMap.get(name, key -> new LocalLock(new ReentrantLock()));
    }
}
